<!--
  功能：考勤录入
  作者：licy
  邮箱：licy@briup.com
  时间：2020年12月08日 11:07:08
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->
<template>
  <div class='attendance_import'>
    <div class="page_title">1. 选择考勤时间</div>
    <div class="box">
      <el-date-picker v-model="form.date" value-format="timestamp" type="date" placeholder="选择日期" />
      <div style="padding:2em 0">
        <el-radio-group v-model="form.stage">
          <el-radio label="上午">上午</el-radio>
          <el-radio label="下午">下午</el-radio>
          <el-radio label="晚自习">晚自习</el-radio>
        </el-radio-group>
      </div>
    </div>
    <div class="page_title">2. 选择考勤班级</div>
    <div class="box">
      <el-cascader filterable v-model="param.dc" clearable :options="directions" placeholder="请选择班级"
        :props="{ children:'clazzes',label:'name',value:'id'}" ></el-cascader>
    </div>
    <div class="page_title">3. 录入考勤日志</div>
    <div style="width:600px;margin:0 auto" v-if="form.date && param.clazzId">
      <el-form size="small" label-width="100px" :model="log_form" :rules="log_rules" ref="log_form">
        <el-form-item label="主讲老师" prop="mainTeacher">
          <el-select filterable v-model="log_form.mainTeacher">
            <el-option v-for="e in employees" :key="e.id" :value="e.realname" :label="e.realname"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="辅导老师" prop="assistTeacher">
          <el-select filterable v-model="log_form.assistTeacher">
            <el-option v-for="e in employees" :key="e.id" :value="e.realname" :label="e.realname"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="course">
          <el-input v-model="log_form.course"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="log_form.comment" type="textarea" :rows="4"></el-input>
        </el-form-item>
        <el-form-item style="text-align:right">
          <el-button type="primary" plain @click="submitClazzLogHandler">提交日志</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-else style="color:red;text-align:center;padding:3em 0">
      请先选择日期和班级
    </div>

    <div class="page_title">4. 录入考勤信息</div>
    <div class="btns">
      <el-form inline size="small">
        <el-form-item>
          <el-input v-model="param.realname"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" icon="el-icon-search" @click="loadStudents">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="form.date && param.clazzId">
      <!-- {{form}} -->
      <div class="student_list" v-loading="loading" >
        <div class="student" v-for="s in studentData.list" :key="s.id">
          <div class="photo">
            <img src="http://121.199.29.84:8888/group1/M00/00/12/rBD-SV-Td6-Aawn0AACq962TS9c719.jpg" alt="">
          </div>
          <div class="info">
            <span><el-checkbox v-model="form.ids" :label="s.id">{{s.realname}}</el-checkbox></span>
          </div>
        </div>
      </div>
      <div class="btns" style="text-align:right">
        <el-button size="mini" type="primary" @click="toSaveAttendance('请假')">请假</el-button>
        <el-button size="mini" type="warning" @click="toSaveAttendance('迟到')">迟到</el-button>
        <el-button size="mini" type="warning" @click="toSaveAttendance('早退')">早退</el-button>
        <el-button size="mini" type="danger" @click="toSaveAttendance('缺课')">缺课</el-button>
      </div>
    </div>
   
    <div v-else style="color:red;text-align:center;padding:3em 0">
      请先选择日期和班级
    </div>

    <div class="page_title">5. 查看考勤信息  <el-button @click="loadAttendances" type="text" size="small">刷新数据</el-button></div>
    <div class="box" v-if="form.date && param.clazzId">
      <el-table :data="attendanceData.list" size="small" v-loading="loading" border >
        <el-table-column type="selection" width="55" align="center" fixed="left" > </el-table-column>
        <el-table-column type="index" :index="1" label="序号" align="center" fixed="left"/>
        <el-table-column prop="student.realname" label="姓名" width="100" align="center" fixed="left" />
        <el-table-column label="性别" prop="student.gender" width="60" align="center" fixed="left"/>
        <el-table-column label="考勤日期" width="120" align="center">
          <template slot-scope="scope">
            {{scope.row.attendanceDate | fmtDate}}
          </template>
        </el-table-column>
        <el-table-column label="考勤阶段" width="100" align="center">
          <template slot-scope="scope">
            {{scope.row.attendanceStage}}
          </template>
        </el-table-column>
        <el-table-column label="缺勤理由" >
          <template slot-scope="scope">
            <el-tag size="small">{{scope.row.status}}</el-tag>
            {{scope.row.comment}}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="100" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="toDeleteHandler(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination background 
        layout="prev, pager, next,sizes" 
        small
        :total="attendanceData.total" 
        :page-size="attendanceData.pageSize" 
        :current-page="attendanceData.page"
        :page-sizes="[5, 10, 15, 20]"
        @size-change="handleSizeChange"
        @current-change="currentChangeHandler">
      </el-pagination>
    </div>
    <div v-else style="color:red;text-align:center;padding:3em 0">
      请先选择日期和班级
    </div>

    <!-- 模态框 -->
    <el-dialog title="考勤" :visible.sync="visible" width="50%" class="customer_modal">
      <div>
        <el-form label-width="100px">
          <el-form-item label="请假模式">
            <el-checkbox v-model="isBatch">批量请假</el-checkbox>
          </el-form-item>
          <div v-show="isBatch">
            <el-form-item label="请假时间" prop="dates">
              <el-date-picker v-model="form.dates" type="daterange" value-format="timestamp" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker>
            </el-form-item>
            <el-form-item label="请假阶段" prop="stages">
                  <el-checkbox-group v-model="form.stages">
                    <el-checkbox label="上午" value="1" ></el-checkbox>
                    <el-checkbox label="下午" value="2"></el-checkbox>
                    <el-checkbox label="晚自习" value="3"></el-checkbox>
                  </el-checkbox-group>
                  
            </el-form-item>
            <el-form-item label="" > 
              <el-checkbox v-model="isAllDay">全天</el-checkbox>
            </el-form-item>
          </div>
          <el-form-item label="备注信息">
            <el-input type="textarea" :rows="4" v-model="form.comment"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="saveAttendance" size="small">确 定</el-button>
      </span>
    </el-dialog>
    <!-- /模态框 -->
  </div>
</template>

<script>
import {get,post} from '@/utils/request'
import {mapGetters} from 'vuex'
import moment from 'moment'
import _ from 'lodash'
export default {
  // 组件名称
  name: 'demo',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data () {
   return {
     visible:false,
     isBatch:false, // 是否批量请假
     loading:false,
     log_form :{

     },
     form:{
      ids:[],
      stages:[]
     },
     param:{
       page:1,
       pageSize:10,
     },
     isAllDay:false,
     directions:[],
     studentData:{list:[]},
     attendanceData:{list:[]},
     log_rules:{
      mainTeacher: [ { required: true, message: '请输入主讲老师', trigger: 'change' } ],
      assistTeacher: [ { required: true, message: '请输入辅导老师', trigger: 'change' } ],
      course: [ { required: true, message: '请输入课程信息', trigger: 'blur' } ],
     },
     employees:[]
   }
  },
  // 计算属性
  computed: {
    attendanceDataFmt(){
      let result = new Map();
      for(let a of this.attendanceData.list){
        // 如果包含
        if(result.has(a.studentId)){

        } else {
          result.set(a.studentId,)
        }
      }
      return result;
    }
  },
  // 侦听器
  watch: {
    isAllDay(now){
      if(now){
        this.form.stages = ['上午','下午','晚自习']
      } else {
        this.form.stages = [];
      }
    },
    'param.dc':{
      handler(now){
        this.param.directionId = now[0];
        this.param.clazzId = now[1];
        // 加载学生，用于提交考勤信息
        this.loadStudents();
        // 加载考勤信息（异常）
        this.loadAttendances();
        // 加载班级日志信息
        this.loadClazzLog();
      }
   }
  },
  // 组件方法
  methods: {
      // 加载讲师信息
    loadEmployees() {
      let url = "/employee/pageQuery"
      get(url,{
        page:1,
        pageSize:100,
        deptId:1  //教学部
      }).then(response => {
        this.employees = response.data.list
      })
    },
    // 删除
    toDeleteHandler(row){
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = '/studentAttendance/deleteById'
        get(url,{id:row.id}).then(response =>{
          this.$message({ type: 'success', message: '删除成功!' });
          this.loadAttendances();
        })
      })
    },
    // 加载班级日志信息
    loadClazzLog(){
      let url = '/clazzLog/findClazzLog'
      let param = {
        logDate:moment(this.form.date).format('YYYY-MM-DD'),
        clazzId:this.param.clazzId
      }
      get(url,param).then(resp=>{
        if(resp.data){
          this.log_form = resp.data?resp.data:{};
        } else {
          // 将上一天的日志调出来
          param.logDate = moment(this.form.date-24*60*60*1000).format('YYYY-MM-DD');
          get(url,param).then(resp=>{
            this.log_form = resp.data?resp.data:{};
          })
        }
      })
    },
    // 提交日志
    submitClazzLogHandler() {
      this.$refs['log_form'].validate((valid) => {
        if (valid) {
          const url = '/clazzLog/saveOrUpdate'
          let form = {
            ...this.log_form,
            clazzId:this.param.clazzId,
            logDate :moment(this.form.date).format('YYYY-MM-DD')
          }
          post(url, form).then(response => {
            this.$message({ message: response.message, type: 'success' })
            // 刷新日志
            this.loadClazzLog();
          })
        } else {
          return false
        }
      })
    },
    // 保存考勤信息
    saveAttendance(){
      let data = _.clone(this.form);
      let url = "/studentAttendance/batchSave"
      if(this.isBatch){
        url = '/studentAttendance/batchSaveMulti'
      }
      post(url,data).then(response => {
        this.$message({ message: response.message, type: 'success' })
        this.visible = false;
        this.loadAttendances();
      });
    },
    // 去保存考勤信息
    toSaveAttendance(status){
      if(this.form.ids && this.form.ids.length > 0){
        this.form = {
          ...this.form,
          status,
          comment :"",
          dates:[],
          stages:[]
        }
        this.isAllDay = false;
        this.visible = true;
      } else {
        this.$message({ message: '请先选择学生', type: 'error' })
      }
    },
    // 加载考勤信息
    loadAttendances(){
      console.log(this.form.ids)
      this.form.ids=[]; 

      let url = "/studentAttendance/pageQuery"
      this.param.attendanceDateStr = moment(this.form.date).format('YYYY-MM-DD');
      let param = _.clone(this.param);
      delete param.dc;
      get(url,param).then(response => {
        this.attendanceData = response.data;
      })
    },
    // 加载方向及班级信息
    loadDirections(){
      let url = "/direction/queryDirectionClazzTree"
      get(url).then(response => {
        this.directions = response.data;
      })
    },
    // 加载学生信息
    loadStudents(){
      this.loading = true;
      let url = '/student/pageQuery'
      let param = _.clone(this.param);
      delete param.dc;
      param.page = 1;
      param.pageSize = 1000;
      get(url,param)
      .then(response => {
        this.studentData = response.data
        this.loading = false;
      })
    },
    // 当前页发生改变
    currentChangeHandler(page){
      this.param.page = page;
      this.loadAttendances();
    },
    // 处理分页大小变化的函数
    handleSizeChange(pageSize){
      // 当前页为第一页
      this.page = 1;
      // 页面大小为用户选择的页面
      this.param.pageSize = pageSize;
      this.loadAttendances();
    },
    // 初始化数据
    initParam(){
      let now = new Date();
      this.form.date = now.getTime();
      let stage = '上午';
      if(now.getHours() > 13 && now.getHours() < 18){
        stage = '下午';
      } else if(now.getHours() > 18) {
        stage = '晚自习';
      }
      this.form = {
        ...this.form,
        stage
      } ;
    }
  },
  // 以下是生命周期钩子
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
  */
  created () {
    this.loadDirections();
    this.initParam();
    this.loadEmployees();
  },
  /**
  * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
  */
  mounted () {
  },
  /**
  * 实例销毁之前调用。在这一步，实例仍然完全可用。
  */
  beforeDestroy () {
  },
  /**
  * Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，
  * 所有的事件监听器会被移除，所有的子实例也会被销毁。
  */
  destroyed () {
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style scoped lang="scss">

.student_list {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  padding: 1em 0;
  .student {
    width: 60px;
    text-align: center;
    margin-right: 15px;
    margin-bottom: 10px;
    
    .photo {
      width: 50px;
      height: 50px;
      margin: 0 auto;
      border-radius: 50%;
      background-color: #f9f9f9;
      overflow: hidden;
      text-align: left;
      img {
        height: 100%;
      }
    }
    .info {
        line-height: 3em;
      }
  }
}



.attendance_import {
  font-size: 12px;
  .page_title {
    text-align: left;
    height: 30px;
    padding:0 2em;
    line-height: 30px;
    background-color: #f4f4f4;
    border-radius: 5px;
    color: #666;
    margin-bottom: .5em;
  }
  .box {
    text-align: center;
    padding: 1em 0;
  }
}
</style>
